package control

import (
	"bms/model"
	"bms/service"
	"html/template"
	"log"
	"net/http"
	"strconv"
	"time"
)

func Index(w http.ResponseWriter, r *http.Request) {
	t := template.Must(template.ParseFiles("view/pages/index.html"))
	t.Execute(w, nil)
}

func Login(w http.ResponseWriter, r *http.Request) {
	//判断是否已经登录过
	flag, _ := IsLogin(r)
	if flag {
		//用户已经登录了，去首页
		GetBookByTitleOrAuthor(w, r)
	} else {
		//用户还没有登录过
		username := r.PostFormValue("username")
		password := r.PostFormValue("password")
		usertype := r.PostFormValue("usertype")
		phone := r.PostFormValue("phone")
		email := r.PostFormValue("email")
		//log.Println("============")
		//log.Println(username, "username")
		//log.Println(password, "password")
		//log.Println(usertype, "usertype")
		//log.Println(phone, "phone")
		//log.Println(email, "email")
		//log.Println("============")
		user := service.GetUser(username, password, usertype, phone, email)
		if user.Id > 0 {
			//创建session
			uuid := model.CreateUUID()
			session := &model.Session{
				SessionId: uuid,
				Username:  user.Username,
				UserId:    user.Id,
			}
			//将session添加的数据库中
			err := service.AddSession(session)
			if err != nil {
				panic(err)
				return
			}
			//设置cookie
			cookie := http.Cookie{
				Name:  "user",
				Value: uuid,
			}
			http.SetCookie(w, &cookie)
			if user.Usertype == "普通用户" {
				t := template.Must(template.ParseFiles("view/pages/user/login_user.html"))
				t.Execute(w, user)
			} else {
				t := template.Must(template.ParseFiles("view/pages/admin/login_admin.html"))
				t.Execute(w, user)
			}
		} else {
			t := template.Must(template.ParseFiles("view/pages/user/login.html"))
			t.Execute(w, "普通用户或管理员信息不正确")
		}
	}
}

//ajax校验用户名是否已存在，用户名是唯一索引

func CheckUser(w http.ResponseWriter, r *http.Request) {
	username := r.PostFormValue("username")
	user, err := service.CheckUser(username)
	if err != nil {
		return
	}
	if user.Id > 0 {
		w.Write([]byte("用户名已存在"))
	} else {
		w.Write([]byte("用户名还不存在，可以进行注册"))
	}
}

func Regist(w http.ResponseWriter, r *http.Request) {
	//注册账户之前判断数据库中有没有该账户
	username := r.PostFormValue("username")
	password := r.PostFormValue("password")
	phone := r.PostFormValue("phone")
	email := r.PostFormValue("email")
	user, _ := service.CheckUser(username)
	if user.Id > 0 {
		//不能注册
		t := template.Must(template.ParseFiles("view/pages/user/regist.html"))
		t.Execute(w, "该用户名已经存在")
	} else {
		err := service.SaveUser(username, password, phone, email)
		if err != nil {
			return
		}
		t := template.Must(template.ParseFiles("view/pages/user/regist_success.html"))
		t.Execute(w, "注册成功")
	}
}

func Logout(w http.ResponseWriter, r *http.Request) {
	cookie, _ := r.Cookie("user")
	if cookie != nil {
		sessionId := cookie.Value
		err := service.DeleteSession(sessionId)
		if err != nil {
			panic(err)
			return
		}
		//设置cookie失效(cookie.MaxAge<0)
		cookie.MaxAge = -1
		http.SetCookie(w, cookie)
	}
	//注销账户之后去首页
	Index(w, r)
}

func GetAllUser(w http.ResponseWriter, r *http.Request) {
	users, _ := service.GetAllUser()
	t := template.Must(template.ParseFiles("view/pages/admin/user_manage.html"))
	t.Execute(w, users)
}

func ReviseUser(w http.ResponseWriter, r *http.Request) {
	userId, _ := strconv.Atoi(r.FormValue("userId"))
	//判断该用户存在不存在//不存在就不会修改密码
	b := service.QueryUser(int64(userId))
	if b {
		//用户存在
		password := r.FormValue("password")
		createTime := time.Now().Format("2006-01-02 15:04:05")
		user := &model.User{
			Id:         int64(userId),
			Password:   password,
			CreateTime: createTime,
		}
		err := service.ReviseUser(user)
		if err != nil {
			log.Println(err)
			return
		}
		GetAllUser(w, r)
	} else {
		//用户不存在，需要传给前端
		w.Write([]byte("用户不存在"))
	}
}

func DeleteUser(w http.ResponseWriter, r *http.Request) {
	userId, _ := strconv.Atoi(r.FormValue("userId"))
	b := service.QueryUser(int64(userId))
	if b {
		//用户存在
		log.Println(userId, "userId--删除-----")
		err := service.DeleteUser(int64(userId))
		if err != nil {
			return
		}
		GetAllUser(w, r)
	} else {
		w.Write([]byte("用户不存在"))
	}

}

// 判断用户是否登录

func IsLogin(r *http.Request) (bool, *model.Session) {
	cookie, _ := r.Cookie("user")
	var session *model.Session
	if cookie != nil {
		sessionId := cookie.Value
		//根据sessionId查询数据库
		session = service.GetSessionBySessionId(sessionId)
		if session.UserId > 0 {
			return true, session
		}
	}
	return false, session
}
